<template>
  <div class="editpass">
    <el-form
      :model="passForm"
      :rules="passRules"
      status-icon
      label-position="right"
      label-width="100px"
      style="max-width: 500px"
      ref="formRef"
    >
      <el-form-item label="旧密码" prop="oldPass">
        <el-input type="password" v-model="passForm.oldPass" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPass">
        <el-input type="password" v-model="passForm.newPass" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input type="password" v-model="passForm.checkPass" show-password />
      </el-form-item>
    </el-form>
    <div class="btn">
      <el-button type="primary" @click="handleUpdateClick">保存</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, watch, computed } from 'vue'
import { binMsg } from '@/global/api.js'
import { passRules } from './rules/passRules'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { updateUserPassWord } from '@/services/roleCommon.js'
import { ElMessageBox } from 'element-plus'

const route = useRoute()
const store = useStore()

const userInfo = computed(() => store.state.userModule.userInfo)
const passForm = reactive({
  id: userInfo.value.id,
  oldPass: '',
  newPass: '',
  checkPass: ''
})
const formRef = ref(null)

// 点击保存按钮事件
const handleUpdateClick = async () => {
  binMsg().closeAll()
  await formRef.value.validate(async valid => {
    if (valid) {
      if (passForm.newPass !== passForm.checkPass) return binMsg('error', '两次输入的密码不一致！')
      // 发起请求修改密码
      updatePass()
    }
  })
}

// 发起请求修改密码
const updatePass = async () => {
  try {
    await ElMessageBox.confirm('是否确认修改密码？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true
    })
    const { data: res } = await updateUserPassWord(userInfo.value.role, passForm)
    if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
    binMsg('success', res.meta.msg)
    reset()
  } catch (e) {
    binMsg('info', '已取消')
  }
}

// 重置
const reset = () => {
  passForm.oldPass = ''
  passForm.newPass = ''
  passForm.checkPass = ''
  // 对该表单项进行重置，将其值重置为初始值并移除校验结果
  formRef.value.resetFields()
}

// 监听路由的变化，如果离开了当前组件就
watch(
  () => route.path,
  val => {
    if (!val.includes('/home/personal/info')) {
      formRef.value.resetFields()
    }
  }
)
</script>

<style lang="less" scoped>
.editpass {
  .btn {
    padding: 10px 0 0 100px;
  }
}
.el-form-item {
  user-select: none;
}
/deep/ .el-input {
  font-weight: 700 !important;
  height: 100% !important;
}

/deep/ .el-form-item__label {
  font-weight: 700 !important;
}
</style>
